// config/api.js - API配置文件
const API_CONFIG = {
  // 门诊充值记录服务 (8084端口)
  RECHARGE: {
    BASE_URL: 'http://localhost:8084',
    ENDPOINTS: {
      LIST: '/recharge/list',
      DETAIL: '/recharge/detail',
      CREATE: '/recharge/create',
      UPDATE: '/recharge/update',
      DELETE: '/recharge/delete'
    }
  },

  // 就诊人管理服务 (8080端口)
  PATIENT: {
    BASE_URL: 'http://localhost:8080',
    ENDPOINTS: {
      LIST: '/patient/list',
      DETAIL: '/patient/detail',
      ADD: '/patient/add',
      UPDATE: '/patient/update',
      DELETE: '/patient/delete',
      SET_DEFAULT: '/patient/setDefault',
      RELATION_TYPES: '/patient/relationTypes',
      ID_CARD_TYPES: '/patient/idCardTypes'
    }
  },

  // 核酸服务 (8080端口)
  NUCLEIC: {
    BASE_URL: 'http://localhost:8080',
    ENDPOINTS: {
      LIST: '/nucleic/list',
      DETAIL: '/nucleic/detail',
      REPORT: '/nucleic/report'
    }
  },

  // 预约服务 (8080端口)
  APPOINTMENT: {
    BASE_URL: 'http://localhost:8080',
    ENDPOINTS: {
      LIST: '/appointment/list',
      CREATE: '/appointment/create',
      CANCEL: '/appointment/cancel'
    }
  }
}

// 构建完整URL的辅助函数
const buildUrl = (service, endpoint, params = {}) => {
  const baseUrl = API_CONFIG[service].BASE_URL
  const endpointPath = API_CONFIG[service].ENDPOINTS[endpoint]
  
  if (!baseUrl || !endpointPath) {
    console.error('Invalid service or endpoint:', service, endpoint)
    return ''
  }

  let url = `${baseUrl}${endpointPath}`
  
  // 处理路径参数
  if (params.pathParams) {
    Object.keys(params.pathParams).forEach(key => {
      url = url.replace(`{${key}}`, params.pathParams[key])
    })
  }

  // 处理查询参数
  if (params.queryParams) {
    const queryString = Object.keys(params.queryParams)
      .map(key => `${encodeURIComponent(key)}=${encodeURIComponent(params.queryParams[key])}`)
      .join('&')
    if (queryString) {
      url += `?${queryString}`
    }
  }

  return url
}

// 获取请求头
const getHeaders = (includeAuth = true) => {
  const headers = {
    'Content-Type': 'application/json'
  }
  
  if (includeAuth) {
    const token = wx.getStorageSync('token')
    if (token) {
      headers['Authorization'] = `Bearer ${token}`
    }
  }
  
  return headers
}

// 通用请求函数
const request = (service, endpoint, options = {}) => {
  const {
    method = 'GET',
    data = null,
    params = {},
    includeAuth = true,
    showLoading = true,
    loadingText = '加载中...'
  } = options

  const url = buildUrl(service, endpoint, params)
  
  if (!url) {
    return Promise.reject(new Error('Invalid URL'))
  }

  if (showLoading) {
    wx.showLoading({
      title: loadingText
    })
  }

  return new Promise((resolve, reject) => {
    wx.request({
      url,
      method,
      data,
      header: getHeaders(includeAuth),
      success: (res) => {
        if (showLoading) {
          wx.hideLoading()
        }
        
        if (res.statusCode >= 200 && res.statusCode < 300) {
          resolve(res.data)
        } else {
          console.error(`API Error: ${res.statusCode}`, res.data)
          reject(new Error(`HTTP ${res.statusCode}: ${res.data?.message || '请求失败'}`))
        }
      },
      fail: (error) => {
        if (showLoading) {
          wx.hideLoading()
        }
        console.error('Network Error:', error)
        reject(new Error('网络请求失败'))
      }
    })
  })
}

// 充值记录相关API
const recharge = {
  getList: (params) => request('RECHARGE', 'LIST', { params }),
  getDetail: (id) => request('RECHARGE', 'DETAIL', { 
    params: { pathParams: { id } } 
  }),
  create: (data) => request('RECHARGE', 'CREATE', { 
    method: 'POST', 
    data 
  })
}

// 就诊人管理相关API
const patient = {
  getList: () => request('PATIENT', 'LIST'),
  getDetail: (id) => request('PATIENT', 'DETAIL', { 
    params: { pathParams: { id } } 
  }),
  add: (data) => request('PATIENT', 'ADD', { 
    method: 'POST', 
    data 
  }),
  update: (id, data) => request('PATIENT', 'UPDATE', { 
    method: 'PUT', 
    data,
    params: { pathParams: { id } }
  }),
  delete: (id) => request('PATIENT', 'DELETE', { 
    method: 'DELETE',
    params: { pathParams: { id } }
  }),
  setDefault: (id) => request('PATIENT', 'SET_DEFAULT', { 
    method: 'POST',
    params: { pathParams: { id } }
  }),
  getRelationTypes: () => request('PATIENT', 'RELATION_TYPES'),
  getIdCardTypes: () => request('PATIENT', 'ID_CARD_TYPES')
}

// 导出API对象
module.exports = {
  API_CONFIG,
  buildUrl,
  getHeaders,
  request,
  recharge,
  patient
} 